<template>
    <div id="irp-domain" style="max-width: 800px;">
    <div class="bi-toolbar bi-bg-white">
        <el-row>
            <el-button type="button" class="bi-el-btn" @click="saveFolder" :disabled="updateFlag < 2">保存</el-button>
        </el-row>
    </div>
     <el-divider></el-divider>
    <div class="bi-ui-dialog-content">
        <el-form ref="folderItem" class="bi-el-form" :model="folderItem" :rules="rules" label-width="80px">
            <el-form-item label="标识" prop="name">
                <el-input ref="focus_input_folder" class="input-toupper" v-model="folderItem.name"  placeholder="请输入标识"></el-input>
            </el-form-item>
            <el-form-item label="标题" prop="title">
                <el-input v-model="folderItem.title" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item label="所属上级">
                <el-select ref="superior" placeholder="请选择上级" v-model="folderItem.parentTitle" @visible-change="parentTreeChange" popper-class="bi-el-select-panel">
                    <el-option label="" value="" style="height: 100%; padding:0px;">
                        <el-tree
                                :indent=24
                                node-key="id"
                                ref="parentTree"
                                style="overflow: visible"
                                class="bi-el-tree bi-el-tree-dropdown"
                                :data="folderData"
                                :highlight-current="true"
                                :auto-expand-parent="true"
                                @node-click="setParent"
                                :load="queryFolderTree" lazy
                                :expand-on-click-node="false">
                            <template slot-scope="{ node, data }">
                                <span :id="'treeitem'+data.id">
                                    <span :class="data.icon + ' bi-ui-iconfont '"></span>
                                    <span :title="data.label">{{ data.label }}</span>
                                </span>
                            </template>
                        </el-tree>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="说明" prop="desc">
                <el-input type="textarea" v-model="folderItem.desc" placeholder="请输入说明" maxlength="165" :autosize="{minRows:5,maxRows:5}"></el-input>
            </el-form-item>
        </el-form>
    </div>
    </div>
</template>

<script>
import { folderApi } from "@/api/irpApi.js";
import { getWsTitleInSession } from "@/utils/cookies.js";

export default {
    props: {
        // 资源大类
        category: {
            type: String,
            required:true,
            default:''
        },
        currNodeId: {
            type: String,
            required:true,
        },
        parentGuid: {
            type: String,
            required:true,
        },
    },
    data() {
        return {
            folderData: [],                         // 所属目录树形
            folderItem: {},                         // 域、应用系统项
            currNodeGuid: "",                       // 当前节点GUID
            rules: {
                name: [ { required: true, message: '请输入标识', trigger: 'blur' }, { validator: this.checkname, trigger: 'blur'} ],
                title: [ { required: true, message: '请输入标题', trigger: 'blur' }, { validator: this.checkTitle, trigger: 'blur'} ],
                desc: [ { validator: this.checkDesc, trigger: 'blur' } ]
            },
            updateFlag:-1
        }
    },
    watch: {
        folderItem: {
            handler (val,old) {
                if (val && this.updateFlag >= 0 ) {
                    this.updateFlag ++ ;
                }
            },
            deep: true
        },
        updateFlag(newValue){
            this.$emit("modify",newValue >=2);
        },
        currNodeId:{
            handler(newNodeId){
                this.initModifyFolderItem(newNodeId, this.parentGuid);
            },
            immediate: true
        }
    },
    methods: {
        // 创建目录项模板
        createTemplete: function(parent) {
            let folderItem = {};
            folderItem.guid = "";
            folderItem.name = "";
            folderItem.title = "";
            folderItem.desc = "";
            folderItem.parent = parent;
            folderItem.parentTitle = "";
            folderItem.empty = "";
            folderItem.category = this.category;
            folderItem.type = this.$folderEnum.folder;
            this.folderItem = folderItem;
        },
        // 查询目录树形
        queryFolderTree: function(node, resolve) {
            let datas = { "category":this.category, "isNotIncludLeaf":"true" ,"hiddenFolderGuid":this.currNodeGuid};
            if (node.level > 0) {
                datas.pId = node.data.id;
                datas.pType = node.data.type;
                datas.workSpaceTitle =encodeURIComponent(getWsTitleInSession())
                folderApi.queryFolderTree(datas).then((result) => {
                    return resolve(result);
                });
            }
        },
        // 初始化修改目录项
        initModifyFolderItem: function(currNodeId, parent) {
            this.updateFlag = -1
            this.resetForm();
            this.createTemplete(parent);
            this.currNodeGuid = currNodeId;
            this.initQueryFolderItem(currNodeId, parent);
        },
        // 初始化查询目录项
        initQueryFolderItem: function(currNodeId, parent) {
            folderApi.queryFolderItem({ "folderGuid": currNodeId }).then((result) => {
                result.parentTitle = "";
                this.folderItem = result;
                this.initQueryFolderTree(parent)
            });
        },
        // 初始化设置父级目录
        initQueryFolderTree: function(parentKey) {
                let datas = { "category":this.category };
                datas.workSpaceTitle =encodeURIComponent(getWsTitleInSession())

                folderApi.queryFolderTree(datas).then((result) => {
                    this.folderData = result;
                    let folderTree = this.$refs.parentTree
                    folderApi.getFolderNodePath({ "fGuid" : parentKey }).then((result) => {
                        if (result.length > 0) {
                            this.expandByPath(folderTree, parentKey, result, 0)
                        }
                    });
                });
        },
        // 递归加载父级
        expandByPath:function(tree, guid, paths, i) {
                let pNode = tree.getNode(paths[i]);
                if (pNode == null) {
                    return;
                }

                let fNode = tree.getNode(guid);
                if (fNode != null) {
                    if (pNode.id === fNode.id) {
                        tree.setCurrentKey(guid);
                        this.folderItem.parentTitle = fNode.label;
                        this.updateFlag = 0
                    } else {
                        pNode.expand(() => {
                            this.expandByPath(tree, guid, paths, ++i);
                        })
                    }
                } else {
                    pNode.expand(() => {
                        this.expandByPath(tree, guid, paths, ++i);
                    })
                }
        },
        // 重置表单
        resetForm: function() {
            this.folderData = [];
            this.currNodeGuid = "";
            // this.$refs["folderItem"].resetFields();
        },
        // 设置所属目录
        setParent: function(data,node,item) {
            this.folderItem.parentTitle = data.label;
            this.folderItem.parent = data.id;
            this.$refs.superior.handleClose();
        },
        // 标识输入后转成大写
        // onChangeName:function(value){
        //     this.folderItem.name = value.toUpperCase();
        // },
        // 验证标识是否重复
        checkname: function(rule, value, callback) {
            this.folderItem.name = this.folderItem.name.toUpperCase()
            if(value.length > 50){
                callback(new Error('标识长度不能超过50个字符'));
            }else if(!/^[a-zA-Z]\w{0,49}$/.test(value)){
                callback(new Error('标识只能由字母、数字和_组成,并且以字母开头'));
            }else{
                let datas = { "datas": JSON.stringify(this.folderItem) };
                folderApi.checkFolderName(datas).then(res =>{
                    if(res.hassame){
                        callback(new Error('标识不能重复！'));
                    }else{
                        callback();
                    }
                }).catch(error => {
                    console.log(error);
                });
            }
        },
        // 验证标题是否重复
        checkTitle: function(rule, value, callback) {
            if (value.length > 30) {
                callback(new Error('标题长度不能超过30个字符'));
            } else if (/\.$/.test(value)) {
                callback(new Error('标题不能以.结尾'))
            } else if (/[/\\*<>"'\\|?:]/.test(value)) {
                callback(new Error('标题不能包含\\ 、/ 、: 、* 、? 、" 、\' 、< 、> 、|中任意字符'))
            } else {
                let datas = { "datas": JSON.stringify(this.folderItem) };
                folderApi.checkFolderTitle(datas).then(res =>{
                    if (res.hassame) {
                        callback(new Error('标题不能重复！'));
                    } else {
                        callback();
                    }
                }).catch(error => {
                    console.log(error);
                });
            }
        },
        // 验证说明
        checkDesc: function(rule, value, callback) {
            if (value != "") {
                if (/^.*[<|>].*$/.test(value)) {
                    callback(new Error('说明不能包含特殊字符< | >'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        },
        parentTreeChange(isVisible){
            if(isVisible){
                let _this = this;
                setTimeout(function(){
                    let dom = document.querySelector("#treeitem"+_this.folderItem.parent);
                    if(dom){
                        dom.parentElement.parentElement.scrollIntoView({
                            //滚动到指定节点
                            block: 'center', //值有start,center,end，nearest，当前显示在视图区域中间
                            behavior: 'smooth' //值有auto、instant,smooth，缓动动画（当前是慢速的）
                        })
                    }
                },300)
            }
        },
        // 确认操作返回结果
        saveFolder: function() {
            return new Promise((resolve)=>{
                this.folderItem.name = this.folderItem.name.toUpperCase()
                this.$refs["folderItem"].validate((valid) => {
                    if (valid) {
                        this.updateFlag = -1
                        let datas = { "datas": JSON.stringify(this.folderItem) };

                        folderApi.saveFolderItem(datas).then((result) => {
                            this.updateFlag = 1
                            this.$emit("save",result)
                            resolve(result);
                        }).catch((error) => {
                            this.$emit("save",false)
                            resolve(false);
                        });
                    } else {
                        this.$emit("save",false)
                        resolve(false);
                    }
                });
            })
        }
    }
}
</script>
<style scoped>
.input-toupper >>> .el-input__inner {
    text-transform: uppercase;
}
#irp-domain .el-divider--horizontal{
    margin: 5px 0px;
}
</style>
<style>
/* 所属目录下拉框面板高度 */
.irp-folder_parent-popper,
.irp-folder_parent-popper .el-scrollbar__wrap {
    width: 400px;
    height: 150px;
    margin-bottom: 0px !important;
}

.irp-folder_parent-popper .el-scrollbar__bar.is-horizontal {
    display: none;
}

.irp-folder_parent-popper .el-scrollbar__bar.is-vertical {
    display: none;
}

.irp-folder_parent-popper .el-select-dropdown__item {
    overflow: visible;
}
</style>
